package com.agrimall.servlet.admin;

import com.agrimall.entity.User;
import com.agrimall.service.OrderService;
import com.agrimall.service.ProductService;
import com.agrimall.service.UserService;
import com.agrimall.service.impl.OrderServiceImpl;
import com.agrimall.service.impl.ProductServiceImpl;
import com.agrimall.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 管理员首页Servlet
 */
@WebServlet("/admin/index")
public class AdminIndexServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private ProductService productService = new ProductServiceImpl();
    private OrderService orderService = new OrderServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User admin = (User) session.getAttribute("admin");
        
        // 验证管理员登录状态
        if (admin == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        try {
            // 查询所有用户总数
            int userCount = userService.countAllUsers();
            
            // 查询所有商品总数
            int productCount = productService.countAllProducts();
            
            // 查询所有订单总数
            int orderCount = orderService.countAllOrders();
            
            // 查询商户总数（user_type = 1）
            int merchantCount = userService.countUsersByType(1);
            
            // 设置数据到request
            request.setAttribute("userCount", userCount);
            request.setAttribute("productCount", productCount);
            request.setAttribute("orderCount", orderCount);
            request.setAttribute("merchantCount", merchantCount);
            
            // 转发到首页JSP
            request.getRequestDispatcher("/admin/index.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "数据加载失败：" + e.getMessage());
            request.getRequestDispatcher("/admin/index.jsp").forward(request, response);
        }
    }
}

